package com.stdz.counter;

import com.stdz.counter.core.thread.ClearCheckThread;
import com.stdz.counter.core.thread.ConfigRefreshThread;
import com.stdz.counter.core.thread.SyncTaskDispatcherThread;
import com.stdz.counter.utils.ResourceUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author peanut
 */

@SpringBootApplication
@MapperScan("com.stdz.counter.dao")
public class CounterApplication implements ApplicationContextAware {

	private static transient Logger logger = LoggerFactory.getLogger(CounterApplication.class);


	public static void main(String[] args) {
		SpringApplication.run(CounterApplication.class, args);
	}

	@Bean
	public InternalResourceViewResolver setupViewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		/** 设置视图路径的前缀 */
		resolver.setPrefix("/templates/counter/");
		/** 设置视图路径的后缀 */
		resolver.setSuffix(".html");
		return resolver;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		ResourceUtil.init(applicationContext);
		ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
		executorService.scheduleWithFixedDelay(new ConfigRefreshThread(),1, 300, TimeUnit.SECONDS);
		ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
		scheduledExecutorService.scheduleWithFixedDelay(new SyncTaskDispatcherThread(), 5, 1, TimeUnit.SECONDS);

		ExecutorService singleExecutor = Executors.newSingleThreadExecutor();
		singleExecutor.submit(new ClearCheckThread());
	}
}
